package com.yjhb.android.sbz.v2.util

import android.os.CountDownTimer
import com.jojo.android.zxlib.tool.ZxLogTool


/**
 *  创建者 zx
 *  创建时间 2021/4/27 10:47
 */
class CountTimeUtil {
    //目标时间
    var target = 0L
        private set

    //当前时间
    var curr = 0L
        private set

    //刷新频率
    var refreshRate = 1000L
    var listener: OnCountTimeListener? = null
    var countDownTimer: CountDownTimer? = null
    var isRunning = false

    fun startCountTime(target: Long,restart:Boolean) {
        this.target = target
        if (restart){
            curr = 0
            isRunning = false
            listener?.onRefresh(curr, target)
        }
        countDownTimer?.cancel()
        countDownTimer = object : CountDownTimer(target, refreshRate) {
            override fun onFinish() {
                listener?.onCompleteLoop()
                isRunning = false
            }

            override fun onTick(millisUntilFinished: Long) {
                if (isRunning) {
                    curr += refreshRate
                    listener?.onRefresh(curr, target)
                    ZxLogTool.e("onTick", "curr:${curr} target:${target}")
                    if (curr >= target) {
                        countDownTimer?.onFinish()
                        stop()
                    }
                }
                isRunning = true
            }

        }
        countDownTimer?.start()

    }

    fun stop() {
        countDownTimer?.cancel()
        curr = 0
        isRunning = false
    }

    fun pause() {
        countDownTimer?.cancel()
        isRunning = false
    }

    fun restore() {
        startCountTime(target,false)
    }

    fun restart(){
        startCountTime(target,true)
    }


    interface OnCountTimeListener {
        /**
         * 刷新
         */
        fun onRefresh(curr: Long, target: Long)

        fun onCompleteLoop()
    }


}